{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ABU量化系统使用文档 \n",
    "\n",
    "<center>\n",
    "        <img src=\"./image/abu_logo.png\" alt=\"\" style=\"vertical-align:middle;padding:10px 20px;\"><font size=\"6\" color=\"black\"><b>第23节 美股UMP决策</b></font>\n",
    "</center>\n",
    "\n",
    "-----------------\n",
    "\n",
    "作者: 阿布\n",
    "\n",
    "阿布量化版权所有 未经允许 禁止转载\n",
    "\n",
    "[abu量化系统github地址](https://github.com/bbfamily/abu) (欢迎+star)\n",
    "\n",
    "[本节ipython notebook](https://github.com/bbfamily/abu/tree/master/abupy_lecture)\n",
    "\n",
    "上一节通过切割美股市场训练集测试集symbol，分别对切割的训练集和测试集做了回测，本节将示例美股ump主裁，边裁决策。\n",
    "\n",
    "首先导入abupy中本节使用的模块："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "enable example env will only read RomDataBu/df_kl.h5\n"
     ]
    }
   ],
   "source": [
    "# 基础库导入\n",
    "\n",
    "from __future__ import print_function\n",
    "from __future__ import division\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "warnings.simplefilter('ignore')\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import ipywidgets\n",
    "%matplotlib inline\n",
    "\n",
    "import os\n",
    "import sys\n",
    "# 使用insert 0即只使用github，避免交叉使用了pip安装的abupy，导致的版本不一致问题\n",
    "sys.path.insert(0, os.path.abspath('../'))\n",
    "import abupy\n",
    "\n",
    "# 使用沙盒数据，目的是和书中一样的数据环境\n",
    "abupy.env.enable_example_env_ipython()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "disable example env\n"
     ]
    }
   ],
   "source": [
    "from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuFactorBuyBreak\n",
    "from abupy import abu, EMarketTargetType, AbuMetricsBase, ABuMarketDrawing, ABuProgress, ABuSymbolPd\n",
    "from abupy import EMarketTargetType, EDataCacheType, EMarketSourceType, EMarketDataFetchMode, EStoreAbu, AbuUmpMainMul\n",
    "from abupy import AbuUmpMainDeg, AbuUmpMainJump, AbuUmpMainPrice, AbuUmpMainWave, feature, AbuFeatureDegExtend\n",
    "from abupy import AbuUmpEdgeDeg, AbuUmpEdgePrice, AbuUmpEdgeWave, AbuUmpEdgeFull, AbuUmpEdgeMul, AbuUmpEegeDegExtend\n",
    "from abupy import AbuUmpMainDegExtend, ump, Parallel, delayed, AbuMulPidProgress\n",
    "\n",
    "# 关闭沙盒数据\n",
    "abupy.env.disable_example_env_ipython()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面读取上一节存储的训练集和测试集回测数据，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "训练集结果：\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:89418\n",
      "买入后尚未卖出的交易数量:2012\n",
      "胜率:46.5220%\n",
      "平均获利期望:8.4475%\n",
      "平均亏损期望:-5.6229%\n",
      "盈亏比:1.3312\n",
      "所有交易收益比例和:839.4100 \n",
      "所有交易总盈亏和:10000777.4300 \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "测试集结果：\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:29786\n",
      "买入后尚未卖出的交易数量:625\n",
      "胜率:46.5420%\n",
      "平均获利期望:8.4243%\n",
      "平均亏损期望:-5.7298%\n",
      "盈亏比:1.3117\n",
      "所有交易收益比例和:260.3562 \n",
      "所有交易总盈亏和:14980168.6900 \n"
     ]
    }
   ],
   "source": [
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL\n",
    "abu_result_tuple = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                                             custom_name='train_us')\n",
    "abu_result_tuple_test = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                                             custom_name='test_us')\n",
    "ABuProgress.clear_output()\n",
    "print('训练集结果：')\n",
    "metrics_train = AbuMetricsBase.show_general(*abu_result_tuple, returns_cmp=True ,only_info=True)\n",
    "print('测试集结果：')\n",
    "metrics_test  = AbuMetricsBase.show_general(*abu_result_tuple_test, returns_cmp=True, only_info=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 美股训练集主裁, 边裁训练\n",
    "\n",
    "上一节A股的主裁训练示例了使用两个内置主裁和两个自定义主裁的组合，本节只先使用四个内置主裁的组合: AbuUmpMainDeg, AbuUmpMainPrice, AbuUmpMainJump, AbuUmpMainWave\n",
    "\n",
    "下面开始训练主裁，第一次运行select：train main ump，然后点击run select，如果已经训练过可select：load main ump直接读取以训练好的主裁："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "load main ump complete!\n"
     ]
    }
   ],
   "source": [
    "# 需要全局设置为美股市场，在ump会根据市场类型保存读取对应的ump\n",
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "us_ump_deg=None\n",
    "us_ump_price=None\n",
    "us_ump_jump=None\n",
    "us_ump_wave=None\n",
    "# 使用训练集交易数据训练主裁\n",
    "orders_pd_train_us = abu_result_tuple.orders_pd\n",
    "\n",
    "def train_main_ump():\n",
    "    print('AbuUmpMainDeg begin...')\n",
    "    AbuUmpMainDeg.ump_main_clf_dump(orders_pd_train_us, save_order=False, show_order=False)\n",
    "    print('AbuUmpMainPrice begin...')\n",
    "    AbuUmpMainPrice.ump_main_clf_dump(orders_pd_train_us, save_order=False, show_order=False)\n",
    "    print('AbuUmpMainJump begin...')\n",
    "    AbuUmpMainJump.ump_main_clf_dump(orders_pd_train_us, save_order=False, show_order=False)\n",
    "    print('AbuUmpMainDegExtend begin...')\n",
    "    AbuUmpMainWave.ump_main_clf_dump(orders_pd_train_us, save_order=False, show_order=False)\n",
    "    # 依然使用load_main_ump，避免下面多进程内存拷贝过大\n",
    "    load_main_ump()\n",
    "    \n",
    "def load_main_ump():\n",
    "    global us_ump_deg, us_ump_price, us_ump_jump, us_ump_wave\n",
    "    us_ump_deg = AbuUmpMainDeg(predict=True)\n",
    "    us_ump_price = AbuUmpMainPrice(predict=True)\n",
    "    us_ump_jump = AbuUmpMainJump(predict=True)\n",
    "    us_ump_wave = AbuUmpMainWave(predict=True)\n",
    "    print('load main ump complete!')\n",
    "\n",
    "def select(select):\n",
    "    if select == 'train main ump':\n",
    "        train_main_ump()\n",
    "    else:\n",
    "        load_main_ump()\n",
    "\n",
    "_ = ipywidgets.interact_manual(select, select=['train main ump', 'load main ump'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上一节A股的边裁训练也示例了使用两个内置主裁和两个自定义主裁的组合，本节只先使用四个内置主裁的组合: AbuUmpEdgeDeg, AbuUmpEdgePrice, AbuUmpEdgeWave, AbuUmpEdgeFull。\n",
    "\n",
    "如下所示，由于边裁的运行机制，所以边裁的训练非常快，这里直接进行训练："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AbuUmpEdgeDeg begin...\n",
      "please wait! dump_pickle....: /Users/Bailey/abu/data/ump/ump_edge_us_deg_edge\n",
      "AbuUmpEdgePrice begin...\n",
      "please wait! dump_pickle....: /Users/Bailey/abu/data/ump/ump_edge_us_price_edge\n",
      "AbuUmpEdgeWave begin...\n",
      "please wait! dump_pickle....: /Users/Bailey/abu/data/ump/ump_edge_us_wave_edge\n",
      "AbuUmpEegeDegExtend begin...\n",
      "please wait! dump_pickle....: /Users/Bailey/abu/data/ump/ump_edge_us_full_edge\n",
      "fit edge complete!\n"
     ]
    }
   ],
   "source": [
    "# 需要全局设置为美股市场，在ump会根据市场类型保存读取对应的ump\n",
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "\n",
    "print('AbuUmpEdgeDeg begin...')\n",
    "AbuUmpEdgeDeg.ump_edge_clf_dump(orders_pd_train_us)\n",
    "us_edge_deg = AbuUmpEdgeDeg(predict=True)\n",
    "\n",
    "print('AbuUmpEdgePrice begin...')\n",
    "AbuUmpEdgePrice.ump_edge_clf_dump(orders_pd_train_us)\n",
    "us_edge_price = AbuUmpEdgePrice(predict=True)\n",
    "\n",
    "print('AbuUmpEdgeWave begin...')\n",
    "AbuUmpEdgeWave.ump_edge_clf_dump(orders_pd_train_us)\n",
    "us_edge_wave = AbuUmpEdgeMul(predict=True)\n",
    "\n",
    "print('AbuUmpEegeDegExtend begin...')\n",
    "AbuUmpEdgeFull.ump_edge_clf_dump(orders_pd_train_us)\n",
    "us_edge_full = AbuUmpEdgeFull(predict=True)\n",
    "\n",
    "print('fit edge complete!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 使用美股内置主裁，边裁进行回测\n",
    "\n",
    "内置边裁的开启很简单，只需要通过env中的相关设置即可完成，如下所示，分别开启主裁和边裁的4个内置裁判："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 回测时会根据env中的市场读取对应市场的最后测试集交易\n",
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "\n",
    "# 开启主裁\n",
    "abupy.env.g_enable_ump_main_deg_block = True\n",
    "abupy.env.g_enable_ump_main_jump_block = True\n",
    "abupy.env.g_enable_ump_main_price_block = True\n",
    "abupy.env.g_enable_ump_main_wave_block = True\n",
    "# 开启边裁\n",
    "abupy.env.g_enable_ump_edge_deg_block = True\n",
    "abupy.env.g_enable_ump_edge_full_block = True\n",
    "abupy.env.g_enable_ump_edge_price_block = True\n",
    "abupy.env.g_enable_ump_edge_wave_block = True\n",
    "\n",
    "# 回测时需要开启特征生成，因为裁判开启需要生成特征做为输入\n",
    "abupy.env.g_enable_ml_feature = True\n",
    "# 回测时使用上一次切割好的测试集数据\n",
    "abupy.env.g_enable_last_split_test = True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "买入因子，卖出因子等依然使用相同的设置，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 初始化资金500万\n",
    "read_cash = 5000000\n",
    "\n",
    "# 买入因子依然延用向上突破因子\n",
    "buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak},\n",
    "               {'xd': 42, 'class': AbuFactorBuyBreak}]\n",
    "\n",
    "# 卖出因子继续使用上一节使用的因子\n",
    "sell_factors = [\n",
    "    {'stop_loss_n': 1.0, 'stop_win_n': 3.0,\n",
    "     'class': AbuFactorAtrNStop},\n",
    "    {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5},\n",
    "    {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}\n",
    "]\n",
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "完成裁判组合的开启，即可开始回测，回测操作流程和之前的操作一样：\n",
    "\n",
    "下面开始回测，第一次运行select：run loop back ump，然后点击run select_ump，如果已经回测过可select：load test ump data直接从缓存数据读取："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please wait! load_pickle....: /Users/Bailey/abu/data/cache/n5_test_ump_us_capital\n",
      "please wait! load_pickle....: /Users/Bailey/abu/data/cache/n5_test_ump_us_benchmark\n"
     ]
    }
   ],
   "source": [
    "abu_result_tuple_test_ump = None\n",
    "def run_loop_back_ump():\n",
    "    global abu_result_tuple_test_ump\n",
    "    abu_result_tuple_test_ump, _ = abu.run_loop_back(read_cash,\n",
    "                                                 buy_factors,\n",
    "                                                 sell_factors,\n",
    "                                                 choice_symbols=None,\n",
    "                                                 start='2012-08-08', end='2017-08-08')\n",
    "    # 把运行的结果保存在本地，以便之后分析回测使用，保存回测结果数据代码如下所示\n",
    "    abu.store_abu_result_tuple(abu_result_tuple_test_ump, n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                               custom_name='test_ump_us')\n",
    "    ABuProgress.clear_output()\n",
    "\n",
    "def run_load_ump():\n",
    "    global abu_result_tuple_test_ump\n",
    "    abu_result_tuple_test_ump = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                                                 custom_name='test_ump_us')\n",
    "\n",
    "def select_ump(select):\n",
    "    if select == 'run loop back ump':\n",
    "        run_loop_back_ump()\n",
    "    else:\n",
    "        run_load_ump()\n",
    "\n",
    "_ = ipywidgets.interact_manual(select_ump, select=['run loop back ump', 'load test ump data'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面对比美股市场测试集交易开启主裁，边裁拦截和未开启主裁，边裁，结果："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:13064\n",
      "买入后尚未卖出的交易数量:266\n",
      "胜率:47.8414%\n",
      "平均获利期望:8.2604%\n",
      "平均亏损期望:-5.6643%\n",
      "盈亏比:1.3901\n",
      "所有交易收益比例和:132.4139 \n",
      "所有交易总盈亏和:11476020.0300 \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<abupy.MetricsBu.ABuMetricsBase.AbuMetricsBase at 0x14917a780>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AbuMetricsBase.show_general(*abu_result_tuple_test_ump, returns_cmp=True, only_info=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:29786\n",
      "买入后尚未卖出的交易数量:625\n",
      "胜率:46.5420%\n",
      "平均获利期望:8.4243%\n",
      "平均亏损期望:-5.7298%\n",
      "盈亏比:1.3117\n",
      "所有交易收益比例和:260.3562 \n",
      "所有交易总盈亏和:14980168.6900 \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<abupy.MetricsBu.ABuMetricsBase.AbuMetricsBase at 0x138d5cf98>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AbuMetricsBase.show_general(*abu_result_tuple_test, returns_cmp=True, only_info=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的结果可以看出拦截了接近一半多的交易，但是胜率和盈亏比提高的并不多，下面将想其它的办法提高回测效果，如下。\n",
    "\n",
    "\n",
    "### 3. 中美裁判配合决策交易\n",
    "\n",
    "上一节通过A股市场的训练集交易进行了主裁，边裁训练，下面将使用上一节训练的A股市场的裁判和本节训练的几个美股裁判一同进行决策（中美联合决策），示例如何使用不同市场的裁判进行交易决策。\n",
    "\n",
    "备注：下面的运行需要在完成运行第20节，21节的基础上\n",
    "\n",
    "美国方面：还是使用刚刚训练好的四个主裁和四个边裁做为内置主裁进行回测设置，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 回测时会根据env中的市场读取对应市场的最后测试集交易\n",
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "\n",
    "# 开启主裁\n",
    "abupy.env.g_enable_ump_main_deg_block = True\n",
    "abupy.env.g_enable_ump_main_jump_block = True\n",
    "abupy.env.g_enable_ump_main_price_block = True\n",
    "abupy.env.g_enable_ump_main_wave_block = True\n",
    "# 开启边裁\n",
    "abupy.env.g_enable_ump_edge_deg_block = True\n",
    "abupy.env.g_enable_ump_edge_full_block = True\n",
    "abupy.env.g_enable_ump_edge_price_block = True\n",
    "abupy.env.g_enable_ump_edge_wave_block = True\n",
    "\n",
    "# 回测时需要开启特征生成，因为裁判开启需要生成特征做为输入\n",
    "abupy.env.g_enable_ml_feature = True\n",
    "# 回测时使用上一次切割好的测试集数据\n",
    "abupy.env.g_enable_last_split_test = True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "中国方面：把上一节训练的所有A股裁判都做为用户自定义的裁判进行添加到裁判系统中，如下所示：\n",
    "\n",
    "* 注意下面主裁或者边裁的读取都使用了market_name参数，来声明读取的是中国的裁判\n",
    "* 注意下面使用ump.manager.append_user_ump添加的不再是裁判的类名称，需要直接添加裁判对象，具体为什么请阅读源代码\n",
    "* 注意下面还需要把10，30，50，90，120日走势拟合角度特征的AbuFeatureDegExtend，做为回测时的新的视角来录制比赛（记录回测特征），因为裁判里面有AbuUmpEegeDegExtend和AbuUmpMainDegExtend，它们需要生成带有10，30，50，90，120日走势拟合角度特征的回测交易单"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "feature.clear_user_feature()\n",
    "# 10，30，50，90，120日走势拟合角度特征的AbuFeatureDegExtend，做为回测时的新的视角来录制比赛\n",
    "feature.append_user_feature(AbuFeatureDegExtend)\n",
    "\n",
    "# 打开使用用户自定义裁判开关\n",
    "ump.manager.g_enable_user_ump = True\n",
    "# 先clear一下\n",
    "ump.manager.clear_user_ump()\n",
    "\n",
    "# 中国的主裁读取，使用market_name参数\n",
    "cn_ump_deg = AbuUmpMainDeg(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_ump_price = AbuUmpMainPrice(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_ump_deg_extend = AbuUmpMainDegExtend(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_ump_mul = AbuUmpMainMul(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "\n",
    "# 中国的边裁读取，使用market_name参数\n",
    "cn_edge_deg = AbuUmpEdgeDeg(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_edge_price = AbuUmpEdgePrice(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_edge_deg_extend = AbuUmpEegeDegExtend(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "cn_edge_mul = AbuUmpEdgeMul(predict=True, market_name=EMarketTargetType.E_MARKET_TARGET_CN)\n",
    "\n",
    "# 把中国的主裁对象使用append_user_ump添加到系统中\n",
    "ump.manager.append_user_ump(cn_ump_deg)\n",
    "ump.manager.append_user_ump(cn_ump_price)\n",
    "ump.manager.append_user_ump(cn_ump_deg_extend)\n",
    "ump.manager.append_user_ump(cn_ump_mul)\n",
    "\n",
    "# 把中国的边裁对象使用append_user_ump添加到系统中\n",
    "ump.manager.append_user_ump(cn_edge_deg)\n",
    "ump.manager.append_user_ump(cn_edge_price)\n",
    "ump.manager.append_user_ump(cn_edge_deg_extend)\n",
    "ump.manager.append_user_ump(cn_edge_mul)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "完成中美裁判组合的开启，即可开始回测，回测操作流程和之前的操作一样：\n",
    "\n",
    "下面开始回测，第一次运行select：run loop back us&cn，然后点击select_cn_us，如果已经回测过可select：load us&cn data直接从缓存数据读取："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US\n",
    "abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL\n",
    "\n",
    "abu_result_tuple_test_ump_cn_us = None\n",
    "def run_loop_back_cn_us():\n",
    "    global abu_result_tuple_test_ump_cn_us\n",
    "    abu_result_tuple_test_ump_cn_us, _ = abu.run_loop_back(read_cash,\n",
    "                                                           buy_factors,\n",
    "                                                           sell_factors,\n",
    "                                                           choice_symbols=None,\n",
    "                                                           start='2012-08-08', end='2017-08-08')\n",
    "    # 把运行的结果保存在本地，以便之后分析回测使用，保存回测结果数据代码如下所示\n",
    "    abu.store_abu_result_tuple(abu_result_tuple_test_ump_cn_us, n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                               custom_name='test_ump_cn_us')\n",
    "    ABuProgress.clear_output()\n",
    "\n",
    "def run_load_cn_us():\n",
    "    global abu_result_tuple_test_ump_cn_us\n",
    "    abu_result_tuple_test_ump_cn_us = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, \n",
    "                                                 custom_name='test_ump_cn_us')\n",
    "\n",
    "def select_cn_us(select):\n",
    "    if select == 'run loop back us&cn':\n",
    "        run_loop_back_cn_us()\n",
    "    else:\n",
    "        run_load_cn_us()\n",
    "\n",
    "_ = ipywidgets.interact_manual(select_cn_us, select=['run loop back us&cn', 'load us&cn data'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:7003\n",
      "买入后尚未卖出的交易数量:164\n",
      "胜率:49.2218%\n",
      "平均获利期望:7.3537%\n",
      "平均亏损期望:-4.5215%\n",
      "盈亏比:1.5725\n",
      "所有交易收益比例和:93.7551 \n",
      "所有交易总盈亏和:79732733.2900 \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<abupy.MetricsBu.ABuMetricsBase.AbuMetricsBase at 0x15846bb70>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AbuMetricsBase.show_general(*abu_result_tuple_test_ump_cn_us, returns_cmp=True, only_info=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "买入后卖出的交易数量:29786\n",
      "买入后尚未卖出的交易数量:625\n",
      "胜率:46.5420%\n",
      "平均获利期望:8.4243%\n",
      "平均亏损期望:-5.7298%\n",
      "盈亏比:1.3117\n",
      "所有交易收益比例和:260.3562 \n",
      "所有交易总盈亏和:14980168.6900 \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<abupy.MetricsBu.ABuMetricsBase.AbuMetricsBase at 0x155d714e0>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AbuMetricsBase.show_general(*abu_result_tuple_test, returns_cmp=True, only_info=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面最终结果显示中美ump联合决策美股测试集数据后，胜率和盈亏比进一步提升，且交易数量下降到只有7000多笔，75%的交易被决策拦截。\n",
    "\n",
    "**ump的训练结果并不针对某一个择时策略，也并不针对某一个具体市场：**\n",
    "\n",
    "比如使用a策略在b市场进行回测后训练好的ump，亦可以适用于c策略在d市场中的交易回测，你可以不断的训练自己的ump，使用不同的策略，在不同的市场，训练自己独一无二的ump裁决系统，后面的章节会讲到使用pipeline的模式组装多个市场，多个策略训练好的ump，关注公众号更新提醒。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "#### abu量化文档目录章节\n",
    "\n",
    "1. [择时策略的开发](http://www.abuquant.com/lecture/lecture_1.html)\n",
    "2. [择时策略的优化](http://www.abuquant.com/lecture/lecture_2.html)\n",
    "3. [滑点策略与交易手续费](http://www.abuquant.com/lecture/lecture_3.html)\n",
    "4. [多支股票择时回测与仓位管理](http://www.abuquant.com/lecture/lecture_4.html)\n",
    "5. [选股策略的开发](http://www.abuquant.com/lecture/lecture_5.html)\n",
    "6. [回测结果的度量](http://www.abuquant.com/lecture/lecture_6.html)\n",
    "7. [寻找策略最优参数和评分](http://www.abuquant.com/lecture/lecture_7.html)\n",
    "8. [A股市场的回测](http://www.abuquant.com/lecture/lecture_8.html)\n",
    "9. [港股市场的回测](http://www.abuquant.com/lecture/lecture_9.html)\n",
    "10. [比特币，莱特币的回测](http://www.abuquant.com/lecture/lecture_10.html)\n",
    "11. [期货市场的回测](http://www.abuquant.com/lecture/lecture_11.html)\n",
    "12. [机器学习与比特币示例](http://www.abuquant.com/lecture/lecture_12.html)\n",
    "13. [量化技术分析应用](http://www.abuquant.com/lecture/lecture_13.html)\n",
    "14. [量化相关性分析应用](http://www.abuquant.com/lecture/lecture_14.html)\n",
    "15. [量化交易和搜索引擎](http://www.abuquant.com/lecture/lecture_15.html)\n",
    "16. [UMP主裁交易决策](http://www.abuquant.com/lecture/lecture_16.html)\n",
    "17. [UMP边裁交易决策](http://www.abuquant.com/lecture/lecture_17.html)\n",
    "18. [自定义裁判决策交易](http://www.abuquant.com/lecture/lecture_18.html)\n",
    "19. [数据源](http://www.abuquant.com/lecture/lecture_19.html)\n",
    "20. [A股全市场回测](http://www.abuquant.com/lecture/lecture_20.html)\n",
    "21. [A股UMP决策](http://www.abuquant.com/lecture/lecture_21.html)\n",
    "22. [美股全市场回测](http://www.abuquant.com/lecture/lecture_22.html)\n",
    "23. [美股UMP决策](http://www.abuquant.com/lecture/lecture_23.html)\n",
    "\n",
    "abu量化系统文档教程持续更新中，请关注公众号中的更新提醒。\n",
    "\n",
    "#### 《量化交易之路》目录章节及随书代码地址\n",
    "\n",
    "1. [第二章 量化语言——Python](https://github.com/bbfamily/abu/tree/master/ipython/第二章-量化语言——Python.ipynb)\n",
    "2. [第三章 量化工具——NumPy](https://github.com/bbfamily/abu/tree/master/ipython/第三章-量化工具——NumPy.ipynb)\n",
    "3. [第四章 量化工具——pandas](https://github.com/bbfamily/abu/tree/master/ipython/第四章-量化工具——pandas.ipynb)\n",
    "4. [第五章 量化工具——可视化](https://github.com/bbfamily/abu/tree/master/ipython/第五章-量化工具——可视化.ipynb)\n",
    "5. [第六章 量化工具——数学：你一生的追求到底能带来多少幸福](https://github.com/bbfamily/abu/tree/master/ipython/第六章-量化工具——数学.ipynb)\n",
    "6. [第七章 量化系统——入门：三只小猪股票投资的故事](https://github.com/bbfamily/abu/tree/master/ipython/第七章-量化系统——入门.ipynb)\n",
    "7. [第八章 量化系统——开发](https://github.com/bbfamily/abu/tree/master/ipython/第八章-量化系统——开发.ipynb)\n",
    "8. [第九章 量化系统——度量与优化](https://github.com/bbfamily/abu/tree/master/ipython/第九章-量化系统——度量与优化.ipynb)\n",
    "9. [第十章 量化系统——机器学习•猪老三](https://github.com/bbfamily/abu/tree/master/ipython/第十章-量化系统——机器学习•猪老三.ipynb)\n",
    "10. [第十一章 量化系统——机器学习•ABU](https://github.com/bbfamily/abu/tree/master/ipython/第十一章-量化系统——机器学习•ABU.ipynb)\n",
    "11. [附录A 量化环境部署](https://github.com/bbfamily/abu/tree/master/ipython/附录A-量化环境部署.ipynb)\n",
    "12. [附录B 量化相关性分析](https://github.com/bbfamily/abu/tree/master/ipython/附录B-量化相关性分析.ipynb)\n",
    "13. [附录C 量化统计分析及指标应用](https://github.com/bbfamily/abu/tree/master/ipython/附录C-量化统计分析及指标应用.ipynb)\n",
    "\n",
    "[更多阿布量化量化技术文章](http://www.abuquant.com/article)\n",
    "\n",
    "\n",
    "更多关于量化交易相关请阅读[《量化交易之路》](http://www.abuquant.com/books/quantify-trading-road.html)\n",
    "\n",
    "更多关于量化交易与机器学习相关请阅读[《机器学习之路》](http://www.abuquant.com/books/machine-learning-road.html)\n",
    "\n",
    "更多关于abu量化系统请关注微信公众号: abu_quant\n",
    "\n",
    "\n",
    "![](./image/qrcode.jpg)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
